/*
 * Copyright © 2022-now 尛飛俠（Denvie） All rights reserved.
 */

package cn.denvie.springcloud.seata.account.controller;

import cn.denvie.springcloud.seata.account.service.AccountService;
import cn.denvie.springcloud.seata.common.model.entity.Account;
import cn.denvie.springcloud.seata.common.model.vo.ResultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * Account控制器。
 *
 * @author Denvie
 * @date 2022/4/08
 * @since 1.0.0
 */
@RestController
@RequestMapping("/account")
public class AccountController {
    @Autowired
    private AccountService accountService;

    /**
     * 获取账户信息。
     * http://localhost:8610/account/getByUserId?userId=ACCOUNT10000
     */
    @RequestMapping("/getByUserId")
    public ResultVo<Account> getByUserId(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new RuntimeException("userId can not be empty.");
        }
        return ResultVo.ok(accountService.getByUserId(userId));
    }

    /**
     * 扣减账户余额。
     * http://localhost:8610/account/debit?userId=ACCOUNT10000&money=10
     */
    @RequestMapping("/debit")
    public ResultVo<Void> debit(String userId, int money) throws InterruptedException {
        // 用户账户扣款
        accountService.debit(userId, money);
        // 当 money > 50 时，休眠8秒，模拟网络响应异常
        if (money > 50) {
            TimeUnit.SECONDS.sleep(8);
        }
        return ResultVo.ok();
    }
}
